package com.atguigu.gmall.product.service;

import com.atguigu.gmall.common.cache.GmallCache;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.model.product.*;
import com.atguigu.gmall.product.mapper.*;
import com.atguigu.gmall.service.RabbitService;
import com.atguigu.gmall.service.config.MqConst;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class ManagerServiceImpl implements ManagerService {

    @Autowired
    private BaseCategory1Mapper baseCategory1Mapper;
    @Autowired
    private BaseCategory2Mapper baseCategory2Mapper;
    @Autowired
    private BaseCategory3Mapper baseCategory3Mapper;

    @Autowired
    private BaseAttrInfoMapper baseAttrInfoMapper;
    @Autowired
    private BaseAttrValueMapper baseAttrValueMapper;

    @Autowired
    private BaseTrademarkMapper baseTrademarkMapper;


    //查询一级分类
    @Override
    public List<BaseCategory1> getCategory1() {
        return baseCategory1Mapper.selectList(null);
    }

    @Override
    public List<BaseCategory2> getCategory2(Long category1Id) {
        QueryWrapper wrapper = new QueryWrapper<BaseCategory2>();
        wrapper.eq("category1_id", category1Id);
        List<BaseCategory2> baseCategory2List = baseCategory2Mapper.selectList(wrapper);
        return baseCategory2List;
    }

    @Override
    public List<BaseCategory3> getCategory3(Long category2Id) {
        QueryWrapper wrapper = new QueryWrapper<BaseCategory3>();
        wrapper.eq("category2_id", category2Id);
        List<BaseCategory3> baseCategory3List = baseCategory3Mapper.selectList(wrapper);
        return baseCategory3List;
    }

    @Override
    public List<BaseAttrInfo> attrInfoList(Long category1Id, Long category2Id, Long category3Id) {
        return baseAttrInfoMapper.attrInfoList(category1Id, category2Id, category3Id);
    }

    @Override
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {

        baseAttrInfoMapper.insert(baseAttrInfo);

        baseAttrInfo.getAttrValueList().forEach(baseAttrValue -> {
            baseAttrValue.setAttrId(baseAttrInfo.getId());
            baseAttrValueMapper.insert(baseAttrValue);
        });
    }

    @Override
    public IPage baseTrademark(Integer page, Integer limit) {
        return baseTrademarkMapper.selectPage(new Page(page, limit), null);
    }

    @Override
    public void save(BaseTrademark baseTrademark) {
        baseTrademarkMapper.insert(baseTrademark);
    }

    @Override
    public void removeById(Long id) {
//        QueryWrapper wrapper = new QueryWrapper<BaseTrademark>();
//        wrapper.eq("id",id);
        baseTrademarkMapper.deleteById(id);
    }

    @Override
    public IPage spuInfoList(Integer page, Integer limit, Long category3Id) {

        return spuInfoMapper.selectPage(new Page(page, limit),
                new QueryWrapper<SpuInfo>().eq("category3_id", category3Id));
    }

    @Override
    public List<BaseTrademark> getTrademarkList() {
        return baseTrademarkMapper.selectList(null);
    }

    @Override
    public List<BaseSaleAttr> baseSaleAttrList() {
        return baseSaleAttrMapper.selectList(null);
    }

    @Override
    public void saveSpuInfo(SpuInfo spuInfo) {
        //1.SpuInfo商品表
        spuInfoMapper.insert(spuInfo);
        //2.SpuImages商品图片表
        spuInfo.getSpuImageList().forEach(spuImage -> {
            //设置外键
            spuImage.setSpuId(spuInfo.getId());
            spuImageMapper.insert(spuImage);
        });
        //3.SpuSaleAttr商品销售属性表
        spuInfo.getSpuSaleAttrList().forEach(spuSaleAttr -> {
            //设置外键
            spuSaleAttr.setSpuId(spuInfo.getId());
            spuSaleAttrMapper.insert(spuSaleAttr);
            //4.SpuSaleAttrValue商品销售属性值表
            spuSaleAttr.getSpuSaleAttrValueList().forEach(spuSaleAttrValue -> {
                //设置外键
                spuSaleAttrValue.setSpuId(spuSaleAttr.getSpuId());
                //设置销售属性名称
                spuSaleAttrValue.setSaleAttrName(spuSaleAttr.getSaleAttrName());
                spuSaleAttrValueMapper.insert(spuSaleAttrValue);
            });
        });
    }

    @Override
    public List<SpuImage> spuImageList(Long spuId) {
        return spuImageMapper.selectList(
                new QueryWrapper<SpuImage>().eq("spu_id", spuId));
    }

    @Override
    public List<SpuSaleAttr> spuSaleAttrList(Long spuId) {
        return spuSaleAttrMapper.spuSaleAttrList(spuId);
    }

    @Override
    public void saveSkuInfo(SkuInfo skuInfo) {
        //1.skuInfo库存表
        skuInfoMapper.insert(skuInfo);
        //2.skuAttrValue库存销售属性中间表
        skuInfo.getSkuAttrValueList().forEach(skuAttrValue -> {
            //设置外键
            skuAttrValue.setSkuId(skuInfo.getId());
            skuAttrValueMapper.insert(skuAttrValue);
        });
        //3.skuSaleAttrValue库存销售属性值表
        skuInfo.getSkuSaleAttrValueList().forEach(skuSaleAttrValue -> {
            //设置外键
            skuSaleAttrValue.setSkuId(skuInfo.getId());
            skuSaleAttrValue.setSpuId(skuInfo.getSpuId());
            skuSaleAttrValueMapper.insert(skuSaleAttrValue);
        });
        //4.skuImageList库存图片表
        skuInfo.getSkuImageList().forEach(skuImage -> {
            //设置外键
            skuImage.setSkuId(skuInfo.getId());
            skuImageMapper.insert(skuImage);
        });
    }

    @Override
    public IPage list(Integer page, Integer limit) {
        return skuInfoMapper.selectPage(new Page(page, limit), null);
    }

    @Autowired
    private RabbitService rabbitService;
    @Override
    public void onSale(Long skuId) {
        //1.数据库修改is_sale字段
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(SkuInfo.IsSale);
        skuInfoMapper.updateById(skuInfo);
        //2.todo   mq发消息，更新索引
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_GOODS,
                    MqConst.ROUTING_GOODS_UPPER,skuId);
    }

    @Override
    public void cancelSale(Long skuId) {
        //1.数据库修改is_sale字段
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(SkuInfo.IsNotSale);
        skuInfoMapper.updateById(skuInfo);
        //2.todo    mq发消息 删除索引
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_GOODS,
                MqConst.ROUTING_GOODS_LOWER,skuId);
    }

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redissonClient;

    //一、查询库存信息&查询图片
    //直接使用RedissonClient来解决分布式锁问题
    @Override
//    @Transactional //开启事务
//    @GmallCache(prefix = "sku:")
    public SkuInfo getSkuInfo(Long skuId) {
        String cacheKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKUKEY_SUFFIX;
        //1.先查询缓存
        SkuInfo skuInfo = (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
        if (null == skuInfo){
            //查询前先上锁，解决缓存击穿
            String cacheLockKey = RedisConst.SKUKEY_PREFIX + skuId +RedisConst.SKULOCK_SUFFIX;
            RLock lock = redissonClient.getLock(cacheLockKey);
            //查询前先上锁，过期不候锁 JUC
            //arg1 获取锁的时间 arg2 获取锁后，锁的过期时间 arg3 单位
            try {
                boolean trylock = lock.tryLock(5, 10, TimeUnit.SECONDS);
                if (trylock){
                    //获取到锁
                    //2.缓存里没有 查询DB
                    skuInfo = skuInfoMapper.selectById(skuId);
                    //一 skuImage图片表
                    if (null != skuInfo) {
                        skuInfo.setSkuImageList(
                                skuImageMapper.selectList(
                                        new QueryWrapper<SkuImage>().eq("sku_id", skuId))
                        );
                        //再保存缓存一份 返回
                        redisTemplate.opsForValue().set(cacheKey, skuInfo,//过期时间加随机数，防止缓存雪崩
                                RedisConst.SKUKEY_TIMEOUT + new Random().nextInt(500), TimeUnit.SECONDS);
                    } else {
                        //解决缓存穿透 把空结果缓存一份
                        skuInfo = new SkuInfo();
                        redisTemplate.opsForValue().set(cacheKey, skuInfo,
                                5, TimeUnit.MINUTES);
                    }
                    //解锁 (获取到锁 才解锁)
                    lock.unlock();
                }else {
                    //未获取到锁
                    try {
                        TimeUnit.SECONDS.sleep(2);
                        return (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return skuInfo;
    }
    //根据SkuId获取SkuInfo信息 图片
    //直接使用redis来解决分布式锁问题
    /*@Override
    public SkuInfo getSkuInfo(Long skuId) {
        String cacheKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKUKEY_SUFFIX;
        //1.先查询缓存
        SkuInfo skuInfo = (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
        if (null == skuInfo) {
            //③ 解决缓存击穿问题 使用分布式锁，先得到key值
            //给锁的值设置UUID,删除时可判断
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            String cacheLockKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKULOCK_SUFFIX;
            Boolean lock = redisTemplate.opsForValue().setIfAbsent(cacheLockKey,uuid,2,TimeUnit.SECONDS);
            if (lock) {
                //获取到了锁
                //2.若没有，查询DB
                skuInfo = skuInfoMapper.selectById(skuId);
                //一 skuImage图片表
                if (null != skuInfo) {
                    skuInfo.setSkuImageList(
                            skuImageMapper.selectList(
                                    new QueryWrapper<SkuImage>().eq("sku_id", skuId))
                    );
                    //再保存缓存一份 返回
                    redisTemplate.opsForValue().set(cacheKey, skuInfo,//过期时间加随机数，防止缓存雪崩
                            RedisConst.SKUKEY_TIMEOUT + new Random().nextInt(500), TimeUnit.SECONDS);
                } else {
                    //解决缓存穿透 把空结果缓存一份
                    skuInfo = new SkuInfo();
                    redisTemplate.opsForValue().set(cacheKey, skuInfo,
                            5, TimeUnit.MINUTES);
                }
                //删除锁，防止该服务器宕机后造成死锁
                //并判断是否是自己的锁  防误删
                *//*Object u = redisTemplate.opsForValue().get(cacheLockKey);
                if (uuid.equals(u)){
                    redisTemplate.delete(cacheLockKey);
                }*//*
                //优化之LUA脚本保证删除的原子性
                String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return tostring(redis.call('del',KEYS[1])) else return 0 end";
                this.redisTemplate.execute(new DefaultRedisScript<>(script), Collections.singletonList(cacheLockKey), uuid);
            } else {
                //未获取到锁 查缓存
                try {
                    Thread.sleep(2500);
                    return (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        //3.统一返回
        return skuInfo;
    }*/

    //二、查询一二三级分类
    @Override
    @GmallCache(prefix = "baseCategory:")
    public BaseCategoryView getBaseCategory(Long category3Id) {
        return baseCategoryViewMapper.selectById(category3Id);
    }

    //三、查询销售属性值
    @Override
    @GmallCache(prefix = "spuSaleAttr:")
    public List<SpuSaleAttr> getSaleAttrListChecked(Long skuId, Long spuId) {
        return spuSaleAttrMapper.getSaleAttrListChecked(skuId, spuId);
    }

    //四、销售属性值组合以及对应库存id
    @Override
    @GmallCache(prefix = "valueSkuJson:")
    public Map getValuesSkuJson(Long spuId) {
        Map result = new HashMap();
        List<Map> listMap = skuSaleAttrValueMapper.getValuesSkuJson(spuId);
        listMap.forEach(map -> {
            result.put(map.get("valueIds"), map.get("sku_id"));
        });
        return result;
    }

    //五、单独查询价格，不走缓存
    @Override
    public BigDecimal getPrice(Long skuId) {
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        if (null != skuInfo){
            return skuInfo.getPrice();
        }else {
            return null;
        }
    }

    @Override
    public List<BaseCategoryView> getBaseCategoryList() {
        return baseCategoryViewMapper.selectList(null);
    }

    @Override
    public BaseTrademark getBaseTrademark(Long id) {
        return baseTrademarkMapper.selectById(id);
    }
    @Override
    public List<SkuAttrValue> getSkuAttrValue(Long skuId) {
        return skuAttrValueMapper.getSkuAttrValue(skuId);
    }

    @Autowired
    private BaseCategoryViewMapper baseCategoryViewMapper;

    @Autowired
    private SkuInfoMapper skuInfoMapper;
    @Autowired
    private SkuAttrValueMapper skuAttrValueMapper;
    @Autowired
    private SkuSaleAttrValueMapper skuSaleAttrValueMapper;
    @Autowired
    private SkuImageMapper skuImageMapper;

    @Autowired
    private SpuInfoMapper spuInfoMapper;
    @Autowired
    private SpuSaleAttrMapper spuSaleAttrMapper;

    @Autowired
    private SpuImageMapper spuImageMapper;
    @Autowired
    private BaseSaleAttrMapper baseSaleAttrMapper;
    @Autowired
    private SpuSaleAttrValueMapper spuSaleAttrValueMapper;


}
